import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  getListDef,
  ableStatus,
  getDetailDef,
  submit,
  updateSubmit,
} from '@/services/productmanage';

export default {
  state: {
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    formFieldsValue: {},
    expandForm: false,
    detailInfo: {},
    valuesArr: [
      'pdName',
      'pdInfo',
      'pdCate',
    ]
  },
  effects: {
    // 获取产品定义查询列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getListDef, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 启用停用状态
    *ableStatus({ payload }, { call }) {
      const response = yield call(ableStatus, payload);
      return response;
    },
    // 详情数据
    *getDetail({ payload }, { call, put }) {
      const response = yield call(getDetailDef, payload);
      if (response.success && response.data) {
        response.data.pdCate = `${response.data.pdCate}`;
        response.data.billFreq = `${response.data.billFreq}`;
        yield put({
          type: 'updateModelData',
          payload: {
            detailInfo: response.data,
          },
        });
      } else {
        message.warning(response.message || '获取产品定义信息：服务端错误');
      }
    },
    // 提交数据
    *submit(
      {
        payload: { values, pdId },
      },
      { call, put }
    ) {
      const submitData = pdId ? { ...values, pdId } : { ...values };
      const response = yield call(pdId ? updateSubmit : submit, submitData);
      if (response.success) {
        message.success(pdId ? '保存成功!' : '新增成功！');
        yield put(
          routerRedux.push({
            pathname: '/productmanage/definition/index',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
  },
  reducers: {
    // 获取产品定价查询列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
